package cn.pinming.except;

import cn.pinming.common.ResponseCode;
import cn.pinming.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

/**
 * <p>
 * spring 异常分为两种（局部和全局）：
 * 局部异常处理 @Controller + @ExceptionHandler
 * 全局异常处理 @ControllerAdvice + @ExceptionHandler
 * </p>
 * <p>参考链接：https://blog.csdn.net/vqhgwjl9eub/article/details/80491196</p>
 *
 * @author wuwanggao@souche.com
 * @version 1.0
 * @description 全局异常处理
 * @date 2019-04-09 15:47
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局运行时异常处理
     *
     * @param e
     * @param response
     * @return
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ServerResponse runtimeException(RuntimeException e, HttpServletResponse response) {
        log.error("全局Runtime异常:e={},response={}", e, response);
        return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(SQLException.class)
    public ServerResponse sqlException(SQLException e, HttpServletResponse response) {
        log.error("全局SQL异常:e={},response={}", e, response);
        return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), e.getMessage());
    }

}
